package org.lyd.spring.aop.proxy.daynamic;

import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @Author:lyd
 **/
public class DynamicProxy {

    //获取被代理对象的代理对象
    public static Object getProxyInstance(Object target) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    String name = method.getName();
                    System.out.println("【log日志】"+name+"开始-->方法执行,参数为："+ Arrays.toString(args));
                    Object result = null;
                    try {
                        result = method.invoke(target, args);
                        System.out.println("【log日志】"+name+"返回-->方法执行,结果为："+ result);
                    } catch (Exception e) {
                        System.out.println("【log日志】"+name+"异常-->"+ e.getMessage());
                    } finally {
                        System.out.println("【log日志】"+name+"结束-->");
                    }
                    return result;
                });
    }
}
